
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:mxh_location/position.dart';

typedef MyCallBack = Function(String val1);
class MxhLocation {

  Stream<String>? _onLocationChanged;
  factory MxhLocation()=> _getInstance();
  static MxhLocation get instance => _getInstance();
  static MxhLocation? _instance;
  MethodChannel _methodChannel;
  EventChannel _eventChannel;
  MxhLocation._internal(this._methodChannel, this._eventChannel) {
    // _eventChannel.receiveBroadcastStream().listen(onEvent, onError: onError);
  }

  static MxhLocation _getInstance() {
    if (_instance == null) {
      MethodChannel methodChannel = MethodChannel('mxh_location');
      EventChannel eventChannel = EventChannel('mxh_location_event');
      _instance = new MxhLocation._internal(methodChannel, eventChannel);
    }
    return _instance!;
  }

  /// 数据接收
  void onEvent(dynamic value) {
    // print("mxh_location onEvent: $value");
  }
  /// 数据接收: 错误处理
  void onError(dynamic value) {
    // print("flutter_mxh_location_event onError: $value");
  }

  //开始定位
  void startLocation() {
    _methodChannel.invokeMethod('startLocation');
    // String str = await _methodChannel.invokeMethod('startLocation');
    // print(str);
  }

  //停止定位
   get stopLocation {
    _methodChannel.invokeMethod('stopLocation');
  }

  Future<String> testandroid() async {
    return await _methodChannel.invokeMethod('testandroid');
  }

  //闭包函数 回调数据传递给使用者
  void listen(void _onData(String event),void _onError(Object error)) {
    _eventChannel.receiveBroadcastStream().listen((event) {
      _onData(event);
    },onError: (Object error){
      _onError(error);
    });
  }

}
